<?php
/**
 * Created by PhpStorm.
 * User: kamlyli
 * Date: 2017/8/5
 * Time: 20:53
 */

namespace app\api\controller\v1;

use app\api\model\Mistake as MistakeModel;
use app\api\model\ProblemDetail;
use think\Request;


class Mistake extends Base
{
    public function get_question()
    {
        // 检查是不是这个人
        $this->check_cookie();

        $mistake = new MistakeModel();
        $mistake = $mistake->where(['userId' => $this->userId, 'state' => 0])->select()->toArray();
        if (!$mistake) {
            return;
        }

        $random_num = array_rand($mistake);
        $problem_id = $mistake[$random_num]['problemId'];

        $problem_detail = new ProblemDetail();
        $problem_detail = $problem_detail->where(['id' => $problem_id])->field(['id', 'type', 'des', 'img', 'optionA', 'optionB', 'optionC', 'optionD'])->find()->toArray();
        if (!$problem_detail) {
            // TODO 记录日志 抛出异常
            return;
        }

        return json_info($problem_detail);
    }

    public function answer_question(Request $request)
    {
        // 检查是不是这个人
        $this->check_cookie();

        // 校验数据 , id , answer,

        // 获取  id , answer,
        $param = $request->param();

        // 判断是不是正确
        $problem_detail = new ProblemDetail();
        $problem_detail = $problem_detail->where('id', $param['id'])->find()->toArray();
        if ($problem_detail['optionRight'] == $param['answer']) {
            $data = [
                'right' => 1,
                'message' => '正确'
            ]; // 正确
        } else {
            $data = [
                'right' => 0,
                'message' => '错误'
            ]; // 错误
        }
        return json_info($data);
    }

    public function del_question($id)
    {
        // 检查是不是这个人
        $this->check_cookie();

        // 校验数据 id

        // 删除数据库
        $mistake = new MistakeModel();
        $mistake = $mistake->where(['problemId' => $id, 'userId' => $this->userId, 'state' => 0])->find();
        if (!$mistake) {
            return;
        }

        $mistake->state = 1;
        $mistake->isUpdate(true)->save();
        return json_info('删除成功');
    }

}